from gtts import gTTS
import os

def convert_text_to_speech(text_file_path, output_audio_path):
    """
    将文本文件内容转换为MP3音频。
    """
    try:
        with open(text_file_path, 'r', encoding='utf-8') as file:
            text_content = file.read()

        if not text_content.strip():
            print("错误：文本文件为空。")
            return

        print("正在进行语音合成...")
        # lang='zh-cn' 表示中文普通话
        tts = gTTS(text=text_content, lang='zh-cn')

        # 保存音频文件
        tts.save(output_audio_path)
        print(f"转换成功！音频已保存为 '{output_audio_path}'。")

    except FileNotFoundError:
        print(f"错误：文件 '{text_file_path}' 未找到。")
    except Exception as e:
        print(f"发生错误: {e}")

if __name__ == '__main__':
    input_file = 'novel.txt'
    output_file = 'out/novel_audio.mp3'
    convert_text_to_speech(input_file, output_file)